<template>
  <!-- 导航栏容器 -->
  <div class="navbar">
    <!-- 左侧导航栏 -->
    <div class="left">

      <!-- 游戏街区logo -->
      <h1 class="logo">
        <div class="logoImg">
          <img src="../assets/logo.png" alt="">
        </div>
        <div class="logoTex">
          <span>游街区</span>
        </div>
      </h1>

      <!-- 导航栏文字 -->
      <div class="Text">
        <div class="TextItem" v-for="item in linkList" :key="item.title" @click="$router.push(item.link)"
          @mouseover="hoverItem = item.title" @mouseleave="hoverItem = null">
          {{ item.title }}
        </div>
      </div>
    </div>


    <!-- 右侧导航栏 -->
    <div class="right">
      <!-- 搜索框 -->
      <div class="search-container">
        <Search :hotSearches="hotSearches" :recentSearches="recentSearches"/>
      </div>
      <div class="post-editor">
        <el-button v-if="!isEditorPage" @click="$router.push('/PostEditor')">发布</el-button>
      </div>

      <!-- 头像 -->
      <div class="userImg">
        <div class="imgBox">
          <img
            :src="userStore.userInfo?.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
            @click="!userStore.userInfo && (showLoginDialog = true)"
            @mouseenter="showUserPopover = userStore.userInfo ? true : false" @mouseleave="handleMouseLeave"
            class="avatar" />
        </div>
      </div>

      <!-- 用户信息浮窗 -->
      <transition name="fade">
        <div v-if="showUserPopover" class="user-popover" @mouseenter="handleMouseEnterPopover"
          @mouseleave="handleMouseLeavePopover">
          <div class="popover-content">
            <div class="user-info">
              <el-avatar :size="60" :src="userStore.userInfo?.avatar" />
              <h3>{{ userStore.userInfo?.username }}</h3>
              <p class="user-id">ID: {{ userStore.userInfo?.id }}</p>
            </div>
            <div class="user-details">
              <p v-for="item in userInfoList" :key="item.label">
                <span>{{ item.label }}:</span> {{ item.value }}
              </p>
            </div>
            <div class="user-actions">
              <p class="action-item" @click="goToProfile">个人中心</p>
              <p class="action-item logout" @click="handleLogout">退出登录</p>
            </div>
          </div>
        </div>
      </transition>
    </div>
  </div>
  <el-dialog v-model="showLoginDialog" style="width: 420px; max-width: 420px;" :modal="true"
    :close-on-click-modal="false" center>
    <div class="dialog-content">
      <LoginForm @success="handleSuccess" />
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import LoginForm from "@/components/LoginForm.vue";
import { useUserStore } from '@/store/user'; // 引入用户状态管理
import { ElMessageBox, ElMessage } from 'element-plus';//
import Search from '@/components/Search.vue'; // 引入搜索组件


const router = useRouter();
// 控制登录对话框显示状态
const showLoginDialog = ref(false);
// 控制用户信息浮窗显示状态（需用户已登录）
const showUserPopover = ref(false);
// 用户状态管理（Pinia store）
const userStore = useUserStore();
const route = useRoute();

// 搜索框图标引用（Element Plus图标组件）
// const Search = ref(null);

// 添加这个计算属性
const isEditorPage = computed(() => {
  return route.meta.isEditorPage;
});

// 导航菜单配置项
// @type {Array<{title: string, link: string}>}
const linkList = ref([
  {
    title: "首页",
    link: "/",
  },
  {
    title: "游戏社区",
    link: "/community",
  },
]);

const handleSuccess = () => {
  showLoginDialog.value = false;
};

let closeTimer = null; // 用于存储定时器

/**
 * 处理鼠标离开头像区域
 * 延迟300ms关闭浮窗避免误触发
 */
const handleMouseLeave = () => {
  closeTimer = setTimeout(() => {
    showUserPopover.value = false;
  }, 300); // 延迟 300ms 关闭浮窗
};

/**
 * 处理鼠标进入浮窗区域
 * 清除关闭定时器保持浮窗显示
 */
const handleMouseEnterPopover = () => {
  clearTimeout(closeTimer); // 鼠标进入浮窗时取消关闭
  showUserPopover.value = true; // 保持浮窗显示
};

/**
 * 处理鼠标离开浮窗区域
 * 立即关闭浮窗
 */
const handleMouseLeavePopover = () => {
  showUserPopover.value = false; // 鼠标离开浮窗时立即关闭
};

/**
 * 处理用户登出操作
 * 1. 清除用户状态
 * 2. 关闭用户信息浮窗
 * 3. 关闭登录弹窗
 */
const handleLogout = async () => {
  try {
    // 弹出确认对话框
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    // 用户确认后执行退出操作
    userStore.clearUserInfo();
    showUserPopover.value = false;
    showLoginDialog.value = false;
    // 提示退出成功
    ElMessage.success('退出登录成功');
  } catch (error) {
    // 用户取消操作
    if (error !== 'cancel') {
      ElMessage.error('退出登录失败');
    }
  }
};

/**
 * 格式化日期
 * @param {string} dateStr - 日期字符串
 * @returns {string} 格式化后的日期
 */
const formatDate = (dateStr) => {
  if (!dateStr) return '未知';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

/**
 * 获取用户信息列表
 * @returns {Array<{label: string, value: string}>}
 */
const userInfoList = computed(() => {
  const user = userStore.userInfo;
  return [
    { label: '手机号', value: user?.phone || '未绑定' },
    { label: '性别', value: user?.gender === 1 ? '男' : '女' },
    { label: '注册时间', value: formatDate(user?.createTime) },
  ];
});

/**
 * 跳转到个人中心
 */
const goToProfile = () => {
  router.push('/profile');
  showUserPopover.value = false;
};
 // 控制搜索建议显示
const recentSearches = ref(['游戏A', '游戏B', '攻略C', '用户D', '社区E']); // 最近搜索数据
const hotSearches = ref(['热门游戏1', '热门游戏2', '热门游戏3', '热门游戏4', '热门游戏5']); // 热榜搜索数据




</script>

<style lang="scss" scoped>
// 新增颜色变量
// Element Plus 主题色（与组件库保持一致）
$primary-color: #409eff;
$hover-bg: rgba($primary-color, 0.1);
$text-color: #606266;
$transition-time: 0.3s;

/* 导航栏根样式
 * 固定宽度居中布局
 * 包含白色背景和细微阴影
 */
.navbar {
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  max-width: 1208px;
  height: 60px;
  padding: 0 20px;
  background: rgba(255, 255, 255);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);



  .left {
    display: flex;
    align-items: center;
    height: 60px;

    .logo {
      display: flex;
      width: 200px;
      height: 60px;

      .logoImg {
        width: 60px;
        height: 60px;
        cursor: pointer;
        margin-right: 20px;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .logoTex {
        width: 60px;
        height: 60px;
        cursor: pointer;

        span {
          font-size: 20px;
          font-weight: 700;
          color: #409eff;
          line-height: 60px;
          text-align: center;
        }
      }
    }

    .Text {
      display: flex;
      align-items: center;
      height: 60px;

      .TextItem {
        cursor: pointer;
        padding: 8px 12px;
        border-radius: 4px;
        transition: all 0.3s;
        color: #606266;

        &:hover {
          color: #409eff;
          background: rgba(64, 158, 255, 0.1);
        }
      }
    }

  }


  .right {
    display: flex;
    align-items: center;


    .search-container {
      position: relative;
      display: flex;
      align-items: center;
      width: 400px;
      height: 60px;
      margin-right: 25px;
    }

    .userImg {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 70px;
      height: 60px;

      .imgBox {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        overflow: hidden;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          transform: scale(1.05);
          box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
        }

        .avatar {
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: 50%;
          transition: all 0.3s;
        }
      }
    }

  }
}

/* 用户信息浮窗样式
 * 定位在头像右侧下方
 * 包含用户名、邮箱和登出按钮
 */
.user-popover {
  position: absolute;
  top: 100%; // 固定在头像下方
  right: 0; // 与头像右对齐
  width: 240px;
  padding: 16px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  margin-top: 10px; // 与头像保持一定距离

  .popover-content {
    .user-info {
      display: flex;
      align-items: center;
      margin-bottom: 16px;

      .el-avatar {
        width: 40px;
        height: 40px;
        margin-right: 12px;
      }

      h3 {
        font-size: 16px;
        font-weight: 500;
        margin: 0;
      }

      .user-id {
        font-size: 12px;
        color: #999;
        margin-left: 8px;
      }
    }

    .user-details {
      background-color: #f8f9fa;
      border-radius: 6px;
      padding: 12px;
      margin-bottom: 16px;

      p {
        font-size: 14px;
        color: #666;
        margin: 0 0 8px 0;

        span {
          color: #333;
          font-weight: 500;
        }
      }
    }
  }
}

/* 浮窗过渡效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity $transition-time ease, transform $transition-time ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

.user-popover {
  .popover-content {
    .user-actions {
      margin-top: 16px;
      border-top: 1px solid #eee;
      padding-top: 12px;

      .action-item {
        font-size: 14px;
        color: #606266;
        padding: 8px 0;
        cursor: pointer;
        transition: color 0.3s;

        &:hover {
          color: #409eff;
        }

        &.logout {
          color: #f56c6c;

          &:hover {
            color: #f78989;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {

  /* 导航栏根样式
 * 固定宽度居中布局
 * 包含白色背景和细微阴影
 */
  .navbar {
    padding: 0 12px;

    .search-container {
      width: 200px;
    }

    .logo .logoTex span {
      display: none; // 小屏幕隐藏文字logo
    }
  }
}
</style>
